package com.mobilekites.adapters;

import android.content.Context;
import android.os.Bundle;
import android.widget.AbsListView.RecyclerListener;
import android.widget.ListView;

import com.android.volley.Response.ErrorListener;
import com.android.volley.VolleyError;
import com.mobilekites.api.model.BucketedList;
import com.mobilekites.util.ErrorStrings;

public abstract class KitesListAdapter<T> extends PaginatedListAdapter
		implements RecyclerListener, ErrorListener {
	private static final String KEY_LISTVIEW = "kites.listview";
	protected BucketedList<T> mBucketedList;

	public KitesListAdapter(Context context, BucketedList<T> bucketedList) {
		super(context, bucketedList.inErrorState(), bucketedList
				.isMoreAvailable());
		mBucketedList = bucketedList;
		mBucketedList.addDataChangedListener(this);
		mBucketedList.addErrorListener(this);
	}

	protected String getLastRequestError() {
		return ErrorStrings.get(mContext, mBucketedList.getVolleyError());
	}

	protected boolean isMoreDataAvailable() {
		return mBucketedList.isMoreAvailable();
	}

	public void onDestroy() {
		mBucketedList.removeDataChangedListener(this);
	}

	public abstract void onDestroyView();

	public void onRestoreInstanceState(ListView listview, Bundle bundle) {
		listview.onRestoreInstanceState(bundle.getParcelable(KEY_LISTVIEW));
	}

	public void onSaveInstanceState(ListView listview, Bundle bundle) {
		bundle.putParcelable(KEY_LISTVIEW, listview.onSaveInstanceState());
	}

	protected void retryLoadingItems() {
		mBucketedList.retryLoadItems();
	}

	public void updateAdapterData(BucketedList<T> bucketedlist) {
		mBucketedList = bucketedlist;
		notifyDataSetChanged();
	}

	@Override
	public void onErrorResponse(VolleyError error) {
		triggerFooterErrorMode();
	}
}
